<template>
  <main>
    <am-container>
      <p> -- 当前操作: {{ crOup }}</p>
      <hr data-am-widget="divider" style="" class="am-divider am-divider-default" />
      <form class="am-form am-form-horizontal" ref="form">
        <fieldset>

          <!-- 作品名称name -->
          <div :class="['am-form-group', 'am-form-group-sm', 'am-form-feedback', { 'am-form-icon am-form-error': !validator.name.vld }]">
            <label for="name" class="am-u-sm-12 am-u-md-2 am-form-label">作品名称</label>
            <div class="am-u-sm-12 am-u-md-10">
              <am-input id="name" placeholder="作品名称" autocomplete="off" v-model="works.name" />
              <template v-if="!validator.name.vld">
                <span class="am-icon-times"></span>
                <small class="am-text-danger">{{ validator.name.msg }}</small>
              </template>
            </div>
            <div class="am-u-end"></div>
          </div>

          <!-- 作品主图mainPic -->
          <div :class="['am-form-group', 'am-form-group-sm', {'am-form-error': !validator.mainPic.vld }]">
            <label class="am-u-sm-12 am-u-md-2 am-form-label" for="mainPic">作品主图</label>
            <div class="am-u-sm-12 am-u-md-10">
              <upload-img ref="mainPic"
                :imgCount.sync="mainPicCount"
                :imgVali.sync="validator.mainPic.vld"
                :imgPath.sync="works.mainPic"
                :listType="'text'"
                :showFileList="false" />

              <template v-if="!validator.mainPic.vld">
                <span class="am-icon-times"></span>
                <small class="am-text-danger">{{ validator.mainPic.msg }}</small>
              </template>
            </div>
            <div class="am-u-end"></div>
          </div>

          <!-- 作品图集worksPic -->
          <div :class="['am-form-group', 'am-form-group-sm', {'am-form-error': !validator.worksPic.vld }]">
            <label class="am-u-sm-12 am-u-md-2 am-form-label" for="worksPic">作品图集</label>
            <div class="am-u-sm-12 am-u-md-10">
              <am-scrollbar :height="300" :auto-hide="false" ref="scrollbar">
                <upload-img ref="pics"
                  :imgCount.sync="worksPicCount"
                  :imgVali.sync="validator.worksPic.vld"
                  :imgPath.sync="works.worksPic"
                  :multiple="true"
                  :showFileList="true"
                  :listType="'picture'" />
              </am-scrollbar>
              <template v-if="!validator.worksPic.vld">
                <span class="am-icon-times"></span>
                <small class="am-text-danger">{{ validator.worksPic.msg }}</small>
              </template>
            </div>
            <div class="am-u-end"></div>
          </div>

          <!-- 全景图url、qart -->
          <div :class="['am-form-group', 'am-form-group-sm', 'am-form-feedback', {'am-form-icon am-form-error': !validator.panoramaUrl.vld}]">
            <label for="panoramaUrl" class="am-u-sm-12 am-u-md-2 am-form-label">全景图地址</label>
            <div class="am-u-sm-12 am-u-md-10">
              <am-input id="panoramaUrl" v-model="works.panoramaUrl" placeholder="全景图地址（自动生成二维码）" autocomplete="off" />
              <template v-if="!validator.panoramaUrl.vld">
                <span class="am-icon-times"></span>
                <small class="am-text-danger">{{ validator.panoramaUrl.msg }}</small>
              </template>
              <br />
              <!-- <vue-q-art :config="qartConfig"></vue-q-art> -->
              <!-- <qr-code :text="works.panoramaUrl"></qr-code> -->
            </div>
            <div class="am-u-sm-12">
              <qr-code :text="works.panoramaUrl"></qr-code>
            </div>
            <div class="am-u-end"></div>
          </div>

          <!-- 分类标签tags -->
          <div :class="['am-form-group', 'am-form-group-sm', {'am-form-error': !validator.worksTag.vld }]">
            <label for="tags" class="am-u-sm-12 am-u-md-2 am-form-label">分类标签</label>
            <div class="am-u-sm-12 am-u-md-3">
              <am-button type="button" @click="showModal">选择分类标签</am-button>
            </div>
            <div class="am-u-sm-12 am-u-md-7">
              <p class="am-text-danger" v-if="!validator.worksTag.vld">{{ validator.worksTag.msg }}</p>
              <p>
                <template v-for="tag in works.worksTag">
                  {{ tag.name }} \
                </template>
              </p>
            </div>
            <div class="am-u-end"></div>
          </div>

          <!-- 业主信息 -->
          <div class="am-form-group">
            <label for="owner" class="am-u-sm-12 am-u-md-2 am-form-label">业主信息</label>
            <div class="am-u-sm-12 am-u-md-5">
              <am-input placeholder="姓名，楼盘，联系方式" :disabled="true"></am-input>
            </div>
            <div class="am-u-end"></div>
          </div>

          <!-- 作品思路 -->
          <div :class="['am-form-group', 'am-form-group-sm', 'am-form-feedback', { 'am-form-icon am-form-error': !validator.introduction.vld }]">
            <label for="introduction" class="am-u-sm-12 am-u-md-2 am-form-label">作品介绍</label>
            <div class="am-u-sm-12 am-u-md-10">
              <am-input id="introduction" type="textarea" rows="5" v-model="works.introduction" placeholder="最好结合客户需求（50字以上)" />
              <template v-if="!validator.introduction.vld">
                <span class="am-icon-times"></span>
                <small class="am-text-danger">当前{{ indroCounter }}个字，{{ validator.introduction.msg }}</small>
              </template>
            </div>
            <div class="am-u-end"></div>
          </div>

          <!-- 作品上传提交 -->
          <div class="am-form-group">
            <div class="am-u-sm-10 am-u-sm-offset-2">
              <am-button type='button' v-if="!submitAbled" disabled>确认添加（请完善信息）</am-button>
              <am-button type="button" v-else @click="beforeSubmit">确认添加</am-button>
            </div>
          </div>
        </fieldset>
      </form>
    </am-container>

    <!-- 模态框 -->
    <modal :modalVisible.sync="modalVisible" :width="450">
      <div slot="选择作品分类标签"></div>
      <tags slot="body" ref="tags" :worksTags.sync="works.worksTag" :tags="tags" />
      <am-button slot="footer" @click="closeModal" color="primary">确认添加</am-button>
    </modal>
  </main>
</template>

<script>
import UploadImg from '@/components/UploadImg'
import Modal from '@/components/Modal'
import Tags from '@/views2/personal/panel/Tags'
import VueQArt from 'vue-qart'
import QrCode from '@/components/QrCode'
import { getDateYMDHS } from '@/util/util'

export default {
  name: 'create',
  data() {
    return {
      mainPicCount: 0,
      worksPicCount: 0,
      tagsData: [],
      isPicReady: {// 图片组件是否回传完成
        mainPic: false,
        pic: false
      },
      modalVisible: false,// 模态框显示
      qartConfig: {// 二维码信息
        value: 'www.baidu.com',// this.works.panoramaUrl
        imagePath: '/static/white.png',// this.works.panoramaPath
        filter: 'color'// threshold 黑白
      },
      works: this.structure.UPLOADWORKS(),// 一个作品
      validator: {// 字段验证
        name: {
          vld: true,
          msg: '名称不能为空'
        },
        mainPic: {
          count: 1,
          vld: true,
          msg: '必须上传一张主图'
        },
        worksPic: {
          count: 2,
          vld: true,
          msg: '选择至少2张图，请重新选择'
        },
        worksTag: {
          vld: true,
          msg: '必须选择一个以上标签'
        },
        panoramaUrl: {
          vld: true,
          msg: '不是合法url地址（请加“http://”前缀）'
        },
        introduction: {
          count: 50,
          vld: true,
          msg: '至少50个字'
        }
      },


      /**
       * 非响应式使用
       */
      validate: {// 验证器
        'works.name': (val = this.works.name) => this.validator.name.vld = !!val,
        'works.mainPic': (val = this.mainPicCount) => this.validator.mainPic.vld = (val === this.validator.mainPic.count),
        'works.worksPic': (val = this.worksPicCount) => this.validator.worksPic.vld = (val >= this.validator.worksPic.count),
        'works.worksTag': (val = this.works.worksTag) => this.validator.worksTag.vld = (val.length > 0),
        // 符合url规则
        'works.panoramaUrl': (val = this.works.panoramaUrl) => this.validator.panoramaUrl.vld = /[a-zA-z]+:\/\/[^\s]*/g.test(val),
        'works.introduction': (val = this.works.introduction) => this.validator.introduction.vld = (val.length >= this.validator.introduction.count)
      },
      loadingIns: {},
    }
  },
  components: {
    UploadImg, VueQArt, Modal, Tags, QrCode
  },
  computed: {
    crOup() {
      if(this.$route.params.id === 'c') {
        return '新增';
      } else {
        return '修改';
      }
    },

    refMainPic() {
      return this.$refs['mainPic'];
    },

    refPics() {
      return this.$refs['pics'];
    },

    /**是否可以提交 */
    submitAbled() {
      if(
        this.mainPicCount !== this.validator.mainPic.count ||
        this.worksPicCount < this.validator.worksPic.count ||
        this.works.name === '' ||
        this.works.worksTag.length === 0 ||
        this.works.introduction < this.validator.introduction.count
      ) {
        return false;
      } else {
        return this.goValidation();
      }
    },

    /**
     * 处理标签规则
     */
    tags() {
      return this.tagsData.map(tag => {
        tag.sub.forEach(subTag => {
          this.$set(subTag, 'color', void 0);// (default)
          this.$set(subTag, 'disabled', false);
        });

        this.$set(tag.main, 'isMulti', false);
        this.$set(tag.main, 'isShow', true);


        /**
         * 三个父标签的规则
         */
        if(tag.main.name === '空间') {
          this.$set(tag.main, 'isMulti', true);
        }

        if(tag.main.name === '全屋定制') {
          this.$set(tag.main, 'isShow', false);
          this.$set(tag.sub[0], 'color', 'primary');
          this.$set(tag.sub[0], 'disabled', true);
        }

        if(tag.main.name === '颜色') {
          this.$set(tag.main, 'isMulti', true);
        }

        return {
          main: tag.main,
          sub: tag.sub
        }
      });
    },

    /**
     * 作品介绍字数
     */
    indroCounter() {
      return this.works.introduction.length;
    }
  },
  methods: {
    ready() {
      this.loadTagsData();
      this.$store.commit('clearTags');
      this.setDesignerID();
    },

    /**设计师id号 */
    setDesignerID() {
      this.works.designerID = this.designerID;
    },

    /**显示标签模态框 */
    showModal() {
      this.modalVisible = true;
    },

    /**提交前的表单验证 */
    goValidation() {
      let isPass = true;// 表单是否通过所有验证
      Object.values(this.validate).forEach(fun => {
        // 提交前把所有validate走一遍
        isPass = fun() && isPass;
      });
      return isPass;
    },

    /**先执行上传，用以触发submit */
    beforeSubmit() {
      this.loadingIns = this.$loading({ loadingText: '正在处理，上传作品成功后请等待审核通过' });
      const dateStr = getDateYMDHS();
      this.$refs.mainPic.submit(dateStr);
      this.$refs.pics.submit(dateStr);
    },

    submit() {// h5原生验证、提交
      const delay = 999;
      Promise.resolve()
      .then(() => {
        this.works.worksPic = this.works.worksPic.toString();
        this.works.worksTag = this.works.worksTag.toString();
        return this.dgpost(this.api.UPLOADWORKS, this.works);
      }).then(res => {
        console.log('创建作品成功');
        setTimeout(() => {
          this.loadingIns.close();
        }, delay);

        this.$parent.curTab = 0;
        setTimeout(() => {
          this.$router.push('/personal/panel/table');
        }, (delay * 1.2));
      }).catch(err => {
        this.loadingIns.close();
        this.$message({
          title: '创建出错',
          type: 'error',
          message: err.msg || this.MSG.UNKNOWN
        });

      });
    },

    /**标签数据 */
    loadTagsData() {
      return new Promise((resolve, reject) => {
        this.dgpost(this.api.GETTAGSDATA, {})
        .then(res => {
          // this.$store.commit('setTags', res.data.data || []);
          this.tagsData = res.data.data || [];
          resolve();
        }).catch(err => {
          this.$message({
            title: '加载标签数据发生错误',
            type: 'error',
            message: err.msg,
            closeable: true
          });
          reject();
        });
      });
    },

    /**
     * 
     */
    btnAct(name) {
      this.funs[name]();
    },
    closeModal() {
      this.modalVisible = false;
    },
  },
  watch: {

    /**
     * 上传完成
     * 替异步做法，触发提交
     */
    'works.mainPic': function(val) {
      this.isPicReady.mainPic = this.validate['works.mainPic']();
    },
    'works.worksPic': function(val) {
      this.isPicReady.pic = this.validate['works.worksPic']();// 主要是数量错误提示
    },
    isPicReady: {
      handler(val) {
        if(val.mainPic === true && val.pic === true) {
          if(this.goValidation()) {
            this.works.worksTag = this.works.worksTag.map(tag => tag.id);
            this.works.panorama = this.qartConfig.value;
            this.submit();
          } else {
            this.loadingIns.close();
            this.$notify({
              message: '请按提示完善信息1',
              type: 'warning'
            });
          }
        }
      },
      deep: true
    },


    /**
     * 输入同时验证
     */
    'works.name': function(val) {
      this.validate['works.name'](val);
    },
    'works.worksTag': function(val) {
      this.validate['works.worksTag'](val);
    },
    'works.panoramaUrl': function(val) {
      this.validate['works.panoramaUrl'](val);
    },
    'works.introduction': function(val) {
      this.validate['works.introduction'](val);
    },
    mainPicCount(val) {
      this.validate['works.mainPic'](val);
    },
    worksPicCount(val) {
      console.log('************** ' + val);
      this.validate['works.worksPic'](val);
    }
  },
  props: {
    designerID: String
  },
  mounted() {
    console.log('123')
    this.ready();
  }
}
</script>